# -*- coding: utf-8 -*-
# @Time       : 2019/7/28 下午12:31
# @Author     : Simon
# @Email      : 
# @File       : ele.py
# @Software   : PyCharm
# @Description:
import datetime
import json
import time
import uuid

import requests
from requests.cookies import RequestsCookieJar

from LoggerWarpper import logger


class ELESpider():
    def __init__(self,cookie):
        # cookie='eleshopid=169623950; eleksid=ZTNHMGMTA1MjEyNzY3MTM4NjAxTW95MStodzZQ'
        self.headers = {
            "Accept": "application/json, text/plain, */*",
            "content-type":"application/json;charset=UTF-8",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",

        }
        self.headers['Cookie'] = cookie

        self.cookie=cookie
        self.base_url = 'https://melody.shop.ele.me'  # 外卖后台地址
        self.api_url='https://app-api.shop.ele.me'
        self.bussinesstatus_url = self.base_url + '/shop/invoke/?method=queryShop.getAllShops'  # 获取商店状态

        self.req=requests.session()
        self.csftoken=None
        self.reqcookie=RequestsCookieJar()
        self.setCookie()
        self.shopId=self.reqcookie['eleshopid']
        self.headers['x-shard'] = "shopid={}".format(self.shopId)

        self.ksid=self.reqcookie['eleksid']
    def setCookie(self):
        for c in self.cookie.split(';'):
            try:
                k, v = c.split('=')
                k = k.strip()
                v = v.strip()
                self.reqcookie.set(k, v)
            except:
                logger.debug(c)
                continue
    def genRequestId(self):
        UUID = ((str(uuid.uuid1()).replace("-", "")[:12] + '4' + str(uuid.uuid1()).replace("-", "")[
                                                                 :19]).upper() + "|" + str(int(time.time() * 1000)))
        return UUID
    def getAllOrder(self,beginTime=None,endTime=None,limit=20,offset=0):
        '''
        如果beginTime与endTime都是None的话，这时候就要去访问今天的数据
        如果两个时间是，beginTime：endTime：，都是参数样式的时间就会返回
        :param beginTime:"2019-09-13T00:00:00"
        :param endTime:"2019-09-13T23:59:59"
        :param limit: 返回条数
        :param offset: 偏移量，从第几页开始
        :return: {}
        '''
        url=""
        if beginTime==None and endTime==None:
            url = self.api_url + '/nevermore/invoke/?method=OrderService.queryLatestOrderForPC'
        elif beginTime  and endTime:
            url=self.api_url+'/nevermore/invoke/?method=OrderService.queryOrder'
        else:
            return False#初步判断错误参数
        requestid = self.genRequestId()
        self.headers['Referer']="https://melody-order.faas.ele.me/app/query?shopId=2000078082"
        data = {"id": requestid,
                "metas": {
                    "appName": "bs-river-bid",
                    "appVersion": "5.0.4",
                    "ksid": self.ksid,
                    "key": "1.0.0",
                    "token":None
                },
                "service": "OrderService",
                "method": "queryLatestOrderForPC",
                "params":
                    {
                        "condition":{"limit":limit,"offset":offset,"beginTime": beginTime,"endTime": endTime},
                        "restaurantId": self.shopId,
                        "orderFilter": "ORDER_QUERY_ALL",
                    },
                "ncp": "2.0.0"
                }
        resp = self.req.post(url, json=data, headers=self.headers)
        #logger.info(resp.text)
        try:
            orders = json.loads(resp.text).get("result",{}).get("orders",{})
        except:
            return False
        return orders
    def getShopStatus(self):
        requestid = self.genRequestId()
        url=self.api_url+'/shop/invoke/?method=queryShop.getAllShops'
        self.headers.update(
            {

               "x-eleme-requestid": requestid,

                "x-shard": "shopid={}".format(self.shopId)

            }
        )
        data = {
            "id": requestid,
            "metas": {
                "appName":"melody",
                "appVersion": "1.1.1",
                "ksid": self.ksid
            },
            "service": "queryShop",
            "method": "getAllShops",
            "params": {

            },
            "ncp": "2.0.0"
        }
        resp=self.req.post(url,json=data,headers=self.headers)
        logger.info(resp.text)
        return resp.json()
    def setCustomerPrice(self,price):
        '''
        设置定向出价
        :param price:
        :return:
        '''
        requestid = self.genRequestId()
        url = self.api_url+'/alchemy/invoke/?method=wager.setOrientationCost'
        self.headers['x-eleme-requestid'] = requestid
        self.headers["x-shard"] = "shopid={}".format(self.shopId)

        data = {
        "id": requestid,
        "metas": {
            "appName": "bs-river-bid",
            "appVersion": "4.4.0",
            "ksid": self.ksid  # 登录后返回的ksid，在 浏览器的local storage 里面能找到
        },
        "service": "wager",
        "method": "setOrientationCost",
        "params": {
            "restaurantId": self.shopId,  # 商户ID
            "orientationCostList": [
                {"customName": "null", "cost": 0, "type": 0, "tag": "null", "stoped": "false"},  # 应该是首页推广价
                {"customName": "null", "cost": 0, "type": 1, "tag": "null", "stoped": "false"},  # 应该是分类页推广价
                {"customName": "null", "cost": 0, "type": 2, "tag": "null", "stoped": "false"},  # 应该是搜索页推广价
                {"cost": price, "type": 3},  # 新用户推广价
                {"cost": 0, "type": 4}  # 老用户推广价
            ]},
        "ncp": "2.0.0"
        }
        resp=self.req.post(url,json=data,headers=self.headers)
        logger.info(resp.text)

    def setBaseprice(self,price):
        price = round(float(price / 100), 1)
        url = self.api_url+'/alchemy/invoke/?method=wager.setWagerGrade'
        requestid = self.genRequestId()
        self.headers['x-eleme-requestid'] = requestid
        self.headers["x-shard"] = "shopid={}".format(self.shopId)
        data = {
            "id": requestid,
            "metas": {
                "appName": "bs-river-bid",
                "appVersion": "4.4.0",
                "ksid": self.ksid
            },
            "service": "wager",
            "method": "setWagerGrade",
            "params": {
                "restaurantId": self.shopId,  # 商户id
                "cost": price  # 基础出价
            },
            "ncp": "2.0.0"
        }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)
    def getYestodayOrder(self):
        requestid=self.genRequestId()
        url=self.api_url+'/stats/invoke/?method=SingleRestaurantSaleDataService.queryHistorySaleData'
        self.headers['x-eleme-requestid'] = requestid
        self.headers["x-shard"] = "shopid={}".format(self.shopId)
        yestoday=(datetime.datetime.now().date()-datetime.timedelta(days=1)).strftime("%Y-%m-%d")
        data={
            "id":requestid,
              "metas":{
                  "appName":"melody",
                  "appVersion":"4.4.0",
                  "ksid":self.ksid,
                  "shopId":self.shopId
              },
            "service":"SingleRestaurantSaleDataService",
            "method":"queryHistorySaleData",
            "params":{"shopId":self.shopId,"beginDate":yestoday,"endDate":yestoday},
            "ncp":"2.0.0"
        }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)
        return resp.json()

    def get7DaysExposure(self):
        end = (datetime.datetime.now().date() + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
        start = (datetime.datetime.now().date() + datetime.timedelta(days=-7)).strftime("%Y-%m-%d")
        requestid = self.genRequestId()
        url = self.api_url + '/alchemy/invoke/?method=wager.getUVSummary'
        today = datetime.datetime.now().date().strftime("%Y-%m-%d")
        data = {
            "id": requestid,
            "metas": {
                "appName": "bs-river-bid",
                "appVersion": "4.4.0",
                "ksid": self.ksid
            },
            "service": "wager",
            "method": "getUVSummary",
            "params": {
                "restaurantId": self.shopId,
                "type": '',
                "beginTime": start,
                "endTime": end
            },
            "ncp": "2.0.0"
        }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)
        return resp.json().get("result", {})
    def gettodayExposure(self):
        requestid = self.genRequestId()
        url=self.api_url+'/alchemy/invoke/?method=wager.getUVSummary'
        today = datetime.datetime.now().date().strftime("%Y-%m-%d")
        data={
            "id":requestid,
            "metas":{
                "appName":"bs-river-bid",
                "appVersion":"4.4.0",
                "ksid":self.ksid
            },
            "service":"wager",
            "method":"getUVSummary",
            "params":{
                "restaurantId":self.shopId,
                "type":'',
                "beginTime":today,
                "endTime":today
            },
            "ncp":"2.0.0"
        }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)
        return resp.json()
    def getBlance(self):
        '''
        获取全额
        :return:
        '''
        url=self.api_url+'/alchemy/invoke/?method=wager.getBalance'
        requestid = self.genRequestId()
        data={"id": requestid,
         "metas": {
             "appName": "bs-river-bid",
             "appVersion": "4.4.0",
             "ksid": self.ksid
            },
              "service": "wager",
              "method": "getBalance",
              "params":
                  {
                      "restaurantId": self.shopId,
                      "accountType": "WAGER"
                   },
            "ncp": "2.0.0"
              }
        resp=self.req.post(url,json=data,headers=self.headers)
        logger.info(resp.text)
        blance=resp.json().get("result",0)
        return blance
    def getAdPrice(self):
        requestid=self.genRequestId()
        url=self.api_url+'/alchemy/invoke/?method=wager.getWagerInformation'
        data={
            "id":requestid,
            "metas":{
                "appName":"bs-river-bid",
                "appVersion":"4.4.0",
                "ksid":self.ksid
            },
            "service":"wager",
            "method":"getWagerInformation",
            "params":{
                "restaurantId":self.shopId
            },
            "ncp":"2.0.0"
        }
        resp = self.req.post(url,json=data, headers=self.headers)
        logger.info(resp.text)
        rep = resp.json().get("result",{})
        return rep
    def setOpenStatus(self):
        requestid=self.genRequestId()
        url=self.api_url+'/alchemy/invoke/?method=wager.updateWagerStatus'
        data={
            "id": requestid,
            "metas": {
                "appName": "bs-river-bid",
                "appVersion": "4.4.0",
                "ksid": self.ksid
                },
                "service": "wager",
                "method": "updateWagerStatus",
                "params": {
                "restaurantId": self.shopId,
                "status": "OPEN"
                },
            "ncp": "2.0.0"
            }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)

    def changeAdstatus(self, p):
        flag = "CLOSE"
        if p == 0:
            flag = "OPEN"
        requestid = self.genRequestId()
        url = self.api_url + '/alchemy/invoke/?method=wager.updateWagerStatus'
        data = {
            "id": requestid,
            "metas": {
                "appName": "bs-river-bid",
                "appVersion": "4.4.0",
                "ksid": self.ksid
            },
            "service": "wager",
            "method": "updateWagerStatus",
            "params": {
                "restaurantId": self.shopId,
                "status": flag
            },
            "ncp": "2.0.0"
        }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)
    def setCloseStatus(self):
        requestid=self.genRequestId()
        url=self.api_url+'/alchemy/invoke/?method=wager.updateWagerStatus'
        data={
            "id": requestid,
            "metas": {
                "appName": "bs-river-bid",
                "appVersion": "4.4.0",
                "ksid": self.ksid
                },
                "service": "wager",
                "method": "updateWagerStatus",
                "params": {
                "restaurantId": self.shopId,
                "status": "CLOSE"
                },
            "ncp": "2.0.0"
            }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)
    def getYesOverViewData(self, beginDate, endDate):
        # https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowData
        # https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowData
        url = ""
        if beginDate and endDate:
            url = self.api_url + '/stats/invoke/?method=OverviewService.queryOverviewHistoryData'
        else:
            return False  # 初步判断错误参数
        requestid = self.genRequestId()
        self.headers['Referer'] = "https://melody-stats-next.faas.ele.me/single/stats-center?tab=overview"
        data = {"id": requestid,
                "metas": {
                    "appName": "melody",
                    "appVersion": "4.4.0",
                    "ksid": self.ksid,
                    "shopId": int(self.shopId)
                },
                "service": "OverviewService",
                "method": "queryOverviewHistoryData",
                "params": {
                    "req": {
                        "compareOption": "BEFORE_1_DAY",
                        "beginDate": beginDate,
                        "endDate": endDate,
                        "shopIds": [int(self.shopId)],
                        "isChainShopId": False,
                        "timePeriodEnum": "YESTERDAY"
                    }
                },
                "ncp": "2.0.0"
                }
        resp = self.req.post(url, json=data, headers=self.headers)
        # logger.info(resp.text)
        try:
            result = json.loads(resp.text).get("result", {})
        except:
            return False
        return result
    def getOverViewSevice(self,beginDate,endDate):
        #https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowData
        url = ""
        if beginDate and endDate:
            url = self.api_url + '/stats/invoke/?method=FlowDataService.queryFlowData'
        else:
            return False  # 初步判断错误参数
        requestid = self.genRequestId()
        self.headers['Referer'] = "https://melody-stats-next.faas.ele.me/single/stats-center?tab=flowmeter"
        data = {"id": requestid,
                "metas": {
                    "appName": "melody",
                    "appVersion": "4.4.0",
                    "ksid": self.ksid,
                    "shopId":int(self.shopId)
                },
                "service": "FlowDataService",
                "method": "queryFlowData",
                "params":{
                    "req":{
                        "compareOption":"BEFORE_7_DAYS",
                        "beginDate": beginDate,
                        "endDate": endDate,
                        "shopIds":[int(self.shopId)],
                        "isChainShopId": False,
                        "timePeriodEnum":"NEARLY_7_DAYS"
                    }
                },
                "ncp": "2.0.0"
                }
        resp = self.req.post(url, json=data, headers=self.headers)
        # logger.info(resp.text)
        try:
            result = json.loads(resp.text).get("result", {})
        except:
            return False
        return result
    def getOverViewSeviceTop(self,beginDate,endDate):
        #https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowAreaSummaryData
        url = ""
        if beginDate and endDate:
            url = self.api_url + '/stats/invoke/?method=FlowDataService.queryFlowAreaSummaryData'
        else:
            return False  # 初步判断错误参数
        requestid = self.genRequestId()
        self.headers['Referer'] = "https://melody-stats-next.faas.ele.me/single/stats-center?tab=flowmeter"
        data = {"id": requestid,
                "metas": {
                    "appName": "melody",
                    "appVersion": "4.4.0",
                    "ksid": self.ksid,
                    "shopId":int(self.shopId)
                },
                "service": "FlowDataService",
                "method": "queryFlowAreaSummaryData",
                "params":{
                    "req":{
                        "compareOption":"BEFORE_7_DAYS",
                        "beginDate": beginDate,
                        "endDate": endDate,
                        "shopIds":[int(self.shopId)],
                        "isChainShopId": False,
                        "timePeriodEnum":"NEARLY_7_DAYS"
                    }
                },
                "ncp": "2.0.0"
                }
        resp = self.req.post(url, json=data, headers=self.headers)
        # logger.info(resp.text)
        try:
            result = json.loads(resp.text).get("result", {})
        except:
            return False
        return result

    def getShopRealTimeOrder(self, beginDate):
        '''
        获取实时的有效订单
        :param beginDate:"2019-10-06"
        :return:
        '''
        url = ""
        if beginDate:
            url = self.api_url + '/stats/invoke/?method=OverviewService.queryHomePageData'
        else:
            return False  # 初步判断错误参数
        requestid = self.genRequestId()
        self.headers['Referer'] = "https://melody-dashboard.faas.ele.me/shop/old"
        data = {"id": requestid,
                "metas": {
                    "appName": "melody",
                    "appVersion": "4.4.0",
                    "ksid": self.ksid,
                },
                "service": "OverviewService",
                "method": "queryHomePageData",
                "params": {
                    "req": {
                        "compareOption": "YESTERDAY",
                        "beginDate": beginDate,
                        "endDate": beginDate,
                        "shopIds": [int(self.shopId)],
                        "isChainShopId": False,
                        "timePeriodEnum": "REAL_TIME"
                    }
                },
                "ncp": "2.0.0"
                }
        resp = self.req.post(url, json=data, headers=self.headers)
        # logger.info(resp.text)
        try:
            result = json.loads(resp.text).get("result", {})
        except:
            return False
        return result

    def getExposure(self, beginDate, endDate):
        # https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowData
        url = "https://app-api.shop.ele.me/stats/invoke/?method=OverviewService.queryOverviewRealTimeData"
        requestid = self.genRequestId()
        self.headers['Referer'] = "https://melody-stats-next.faas.ele.me/single/stats-center?tab=overview"
        data = {"id": requestid,
                "metas": {
                    "appName": "melody",
                    "appVersion": "4.4.0",
                    "ksid": self.ksid,
                    "shopId": int(self.shopId)
                },
                "service": "OverviewService",
                "method": "queryOverviewRealTimeData",
                "params": {
                    "req": {
                        "compareOption": "BEFORE_1_DAY",
                        "beginDate": beginDate,
                        "endDate": endDate,
                        "shopIds": [int(self.shopId)],
                        "isChainShopId": False,
                        "timePeriodEnum": "REAL_TIME"
                    }
                },
                "ncp": "2.0.0"
                }
        resp = self.req.post(url, json=data, headers=self.headers)
        # logger.info(resp.text)
        try:
            result = json.loads(resp.text).get("result", {})
        except:
            return False
        return result

    def getSettleBillList(self, beginTimeStamp, endTimeStamp):
        # self.headers['X-Shard'] = "shopId={}".format(self.shopId)
        url = "https://hydrosweb.faas.ele.me/api/v4/bill/dailyBill?restaurantId=" + str(
            self.shopId) + "&beginClosingDate=" + str(beginTimeStamp) + "&endClosingDate=" + str(
            endTimeStamp) + "&status=3&loginRestaurantId=" + str(self.shopId) + "&authType=eleme"
        requestid = self.genRequestId()
        self.headers['Referer'] = "https://hydrosweb.faas.ele.me/checkout?shopId={}".format(self.shopId)
        data = {
            "restaurantId": self.shopId,
            "beginClosingDate": beginTimeStamp,
            "endClosingDate": endTimeStamp,
            "status": "3",
            "loginRestaurantId": self.shopId,
            "authType": "eleme"
        }
        resp = self.req.get(url, params=data, headers=self.headers)
        # logger.info(resp.text)
        try:
            result = json.loads(resp.text).get("result", {})
        except:
            return False
        return result

        # https://app-api.shop.ele.me/stats/invoke/?method=OverviewService.queryOverviewHistoryData
    def getHistoryData(self, beginDate, endDate):
        # https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowData
        # https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowData
        url = ""
        if beginDate and endDate:
            url = self.api_url + '/stats/invoke/?method=OverviewService.queryOverviewHistoryData'
        else:
            return False  # 初步判断错误参数
        requestid = self.genRequestId()
        self.headers['Referer'] = "https://melody-stats-next.faas.ele.me/single/stats-center?tab=overview"
        data = {"id": requestid,
                "metas": {
                    "appName": "melody",
                    "appVersion": "4.4.0",
                    "ksid": self.ksid,
                    "shopId": int(self.shopId)
                },
                "service": "OverviewService",
                "method": "queryOverviewHistoryData",
                "params": {
                    "req": {
                        "compareOption": "BEFORE_7_DAYS",
                        "beginDate": beginDate,
                        "endDate": endDate,
                        "shopIds": [int(self.shopId)],
                        "isChainShopId": False,
                        "timePeriodEnum": "NEARLY_7_DAYS"
                    }
                },
                "ncp": "2.0.0"
                }
        resp = self.req.post(url, json=data, headers=self.headers)
        # logger.info(resp.text)
        try:
            result = json.loads(resp.text).get("result", {})
        except:
            return False
        return result

    def setBudget(self, price):
        price = int(price / 100)
        url = self.api_url + '/alchemy/invoke/?method=wager.setWagerBudget'
        requestid = self.genRequestId()
        self.headers['x-eleme-requestid'] = requestid
        self.headers["x-shard"] = "shopid={}".format(self.shopId)
        data = {
            "id": requestid,
            "metas": {
                "appName": "bs-river-bid",
                "appVersion": "4.4.0",
                "ksid": self.ksid
            },
            "service": "wager",
            "method": "setWagerBudget",
            "params": {
                "budget": str(price),  # 基础出价
                "restaurantId": self.shopId
            },
            "ncp": "2.0.0"
        }
        resp = self.req.post(url, json=data, headers=self.headers)
        logger.info(resp.text)
        result = json.loads(resp.text)
        return result

#https://app-api.shop.ele.me/stats/invoke/?method=FlowDataService.queryFlowAreaSummaryData
if __name__=="__main__":
    cookie = 'eleshopid=169623950; eleksid=ZTNHMGMTA1MjEyNzY3MTM4NjAxTW95MStodzZQ'
    ele=ELESpider(cookie)
    ele.getShopStatus()